package com.cltech.frame.shiro;

import com.cltech.constant.UserState;
import com.cltech.entity.sys.SysUser;
import com.cltech.service.sys.SysUserService;
import com.cltech.frame.utils.JWTUtil;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Set;

import static java.util.stream.Collectors.toSet;

/**
 * Created by Administrator on 2018/9/9.
 */
@Component
public class SysRealm extends AuthorizingRealm {

    private SysUserService sysUserService;

    @Autowired
    public void setSysUserService(SysUserService sysUserService) {
        this.sysUserService = sysUserService;
    }

    /**
     * 大坑！，必须重写此方法，不然Shiro会报错
     */
    @Override
    public boolean supports(AuthenticationToken token) {
        return token instanceof JWTToken;
    }

    /**
     * 只有当需要检测用户权限的时候才会调用此方法，例如checkRole,checkPermission之类的
     */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
        String account = JWTUtil.getAccount(principals.toString());
        SysUser user = sysUserService.findByAccountAndState(account, UserState.NORMAL).getData();
        SimpleAuthorizationInfo simpleAuthorizationInfo = new SimpleAuthorizationInfo();
        simpleAuthorizationInfo.addRoles(user.getRoles().stream().map(sysRole -> sysRole.getRoleCode()).collect(toSet()));
        simpleAuthorizationInfo.addStringPermissions(user.getRoles().stream().map(sysRole -> sysRole.getPermissions()).flatMap(Set::stream).map(permission -> permission.getPermissionCode()).collect(toSet()));
        return simpleAuthorizationInfo;
    }

    /**
     * 默认使用此方法进行用户名正确与否验证，错误抛出异常即可。
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken auth) throws AuthenticationException {
        String token = (String) auth.getCredentials();
        // 解密获得username，用于和数据库进行对比
        String account = JWTUtil.getAccount(token);
        if (account == null) {
            throw new AuthenticationException("token认证失败");
        }
        SysUser user = sysUserService.findByAccountAndState(account,  UserState.NORMAL).getData();
        if (user == null) {
            throw new AuthenticationException("用户不存在");
        }

        if (!JWTUtil.verifyAccessToken(token, account, user.getPassword(), user.getId())) {
            throw new AuthenticationException("用户名或密码错误");
        }
        return new SimpleAuthenticationInfo(token, token, "sys_realm");
    }
}